function Stack () {
    this.dataStore = [];
    this.top = 0;   //栈中最后一个元素（最新添加的元素）的索引
    this.push = push;   //向栈中添加元素的方法
    this.pop = pop;     //弹出并返回栈中最上层元素的方法
    this.peek = peek;   //读取最上层元素的方法
    this.length = length;      //返回栈的长度
    this.clear = clear;         //清空栈
}

let push = function (element) {
    this.dataStore[this.top++] = element;
}

let pop = function () {
    return this.dataStore[--this.top];
}

let peek = function () {
    return this.dataStore[this.top - 1];
}

let length = function () {
    return this.top;
}

let clear = function () {
    this.dataStore = [];
    this.top = 0;
}

let stack = new Stack();
stack.push("test");
console.log(stack.pop());
console.log(stack.peek());

//使用栈递归实现阶乘
function factorial (num) {
    let stack = new Stack();
    for(let i = 1; i <= num; i++) {
        stack.push(i);
    };
    let result = 1;
    while(stack.length() > 0) {
        result *= stack.pop();
    }
    return result;
}

console.log(factorial(2));